package com.yuanfeng.order.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.util.DateUtils;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.vo.fx.GoodsVkSetVO;
import com.yuanfeng.commoms.vo.fx.ShareGoodsVO;
import com.yuanfeng.commoms.vo.fx.VKUserInfoVO;
import com.yuanfeng.commoms.vo.fx.VkApplyOrderVO;
import com.yuanfeng.commoms.vo.order.OrderCommissionVO;
import com.yuanfeng.commoms.vo.order.WapShippingQueryResultVO;
import com.yuanfeng.commoms.vo.order.WapShopShippingQueryResultVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.order.feign.BaseServiceClient;
import com.yuanfeng.order.feign.UserServiceClient;
import com.yuanfeng.order.mapper.OrderBaseMapper;
import com.yuanfeng.order.mapper.OrderCommissionMapper;
import com.yuanfeng.order.service.FXService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fwx
 * @date 2021-06-0510:29
 * @Description: 分销
 **/
@Service
public class FXServiceImpl implements FXService {
    private static final Logger logger = LoggerFactory.getLogger(FXServiceImpl.class);

    @Autowired
    OrderCommissionMapper orderCommissionMapper;
    @Autowired
    private BaseServiceClient baseServiceClient;
    @Autowired
    private UserServiceClient userServiceClient;
    @Autowired
    private OrderBaseMapper orderBaseMapper;

    @Override
    public OrderCommissionVO addOrderCommission(WapShippingQueryResultVO shippingQueryResult, WapShopShippingQueryResultVO shopShippingQueryResult, UserInfoVO userInfo, String shareUserId, String orderId, BigDecimal orderPrice, Integer fxType){
        // 1.查询是否开启微客推广已经分佣业绩归属
        ResponseResult resultResp = baseServiceClient.queryGoodsVkSet();
        GoodsVkSetVO goodsVkSet = JSON.parseObject(JSON.toJSONString(resultResp.getData()),GoodsVkSetVO.class);
        //获取微客绑定的上级
        Map<String,String> map2 = new HashMap<>(8);
        map2.put("userId",userInfo.getUserId());
        resultResp = userServiceClient.queryVKUserInfo(map2);
        VKUserInfoVO shareUserInfo2 = JSON.parseObject(JSON.toJSONString(resultResp.getData()),VKUserInfoVO.class);
        if(StrUtil.isNotBlank(shareUserInfo2.getShopUserId())){
            //证明当前用户是微客 赋值用户的上级用户id
            userInfo.setUserParentId(shareUserInfo2.getShopUserId());
        }else{
            //证明 当前用户是普通用户 赋值上级用户id 为分享人用户id
            userInfo.setUserParentId(shareUserId);
        }
        shippingQueryResult = this.commissionCheck(goodsVkSet,shippingQueryResult,shareUserId,userInfo,fxType);
        if(shippingQueryResult.getTgRate().equals("0") && shippingQueryResult.getFxRate().equals("0")){
            //走到这里说明该商品不是分销商品
            return  null;
        }
        // 2.查询分享微客信息
        Map<String,String> map = new HashMap<>(8);
        map.put("userId",shareUserId);
        resultResp = userServiceClient.queryVKUserInfo(map);
        VKUserInfoVO shareUserInfo = JSON.parseObject(JSON.toJSONString(resultResp.getData()),VKUserInfoVO.class);
        if(shareUserInfo.getVkState() > 0){
            // 3.创建微客订单
            OrderCommissionVO orderCommission = this.buildOrderCommission(shippingQueryResult,shopShippingQueryResult,shareUserInfo,userInfo,orderId,orderPrice);
            return orderCommission;
        }
        return null;
    }

    /**
     * 分佣校验1
     * @param goodsVkSet
     * @param shippingQueryResult
     * @param shareUserId
     * @param userInfo
     * @return
     */
        private WapShippingQueryResultVO commissionCheck(GoodsVkSetVO goodsVkSet,WapShippingQueryResultVO shippingQueryResult,String shareUserId,UserInfoVO userInfo,Integer fxType){
        if(goodsVkSet.getVkState() == 1 && goodsVkSet.getCommisionConfig() != 0){
            // 如果分享用户不是购买用户的上级  或者只开启分享人分佣 则推广佣金为0
//            if(!userInfo.getUserParentId().equals(shareUserId) || goodsVkSet.getCommisionConfig() == 2){
            if(goodsVkSet.getCommisionConfig() == 2){
                shippingQueryResult.setTgRate("0");
            }
            // 如果只开启推广人分佣 则分享佣金为0
            if(goodsVkSet.getCommisionConfig() == 1){
                shippingQueryResult.setFxRate("0");
            }
            // 不是通过分享页 购买的直接在商城购买的 只有推广佣金 没有分享佣金
            if( fxType == 2){
                shippingQueryResult.setFxRate("0");
            }
        }else{
            // 微客推广关闭  无佣金
            shippingQueryResult.setTgRate("0");
            shippingQueryResult.setFxRate("0");
        }
        return shippingQueryResult;
    }

    public OrderCommissionVO buildOrderCommission(WapShippingQueryResultVO shippingQueryResult, WapShopShippingQueryResultVO shopShippingQueryResult,  VKUserInfoVO shareUserInfo,UserInfoVO userInfo, String OrderId,BigDecimal orderPrice){
        OrderCommissionVO orderCommission = new OrderCommissionVO();
        orderCommission.setOrderId(OrderId);
        orderCommission.setGoodsId(shippingQueryResult.getGoodsId());
        orderCommission.setGoodsName(shippingQueryResult.getGoodsName());
        orderCommission.setGoodsPrice(shippingQueryResult.getGoodsPrice());
        orderCommission.setGoodsNum(shippingQueryResult.getGoodsNum());
        orderCommission.setGoodsImage(shippingQueryResult.getGoodsImage());
        orderCommission.setCatId(shippingQueryResult.getCatId());
        orderCommission.setShopId(shopShippingQueryResult.getShopId());
        orderCommission.setShareUserId(shareUserInfo.getUserId());
        orderCommission.setShareUserName(shareUserInfo.getUserName());
        orderCommission.setShareUserMobile(shareUserInfo.getUserMobile());
        orderCommission.setShareUserShopId(shareUserInfo.getShopId());
        orderCommission.setShareUserStoreId(shareUserInfo.getStoreId());
        orderCommission.setShareUserStoreName(shareUserInfo.getStoreName());
        orderCommission.setBuyUserId(userInfo.getUserId());
        orderCommission.setBuyUserName(userInfo.getUserName());
        orderCommission.setBuyUserMobile(userInfo.getUserMobile());
        orderCommission.setBuyUserAvatar(userInfo.getUserAvatar());
        orderCommission.setBuyUserTime(userInfo.getUserLastloginTime());
        orderCommission.setOrderStatus(CommonType.CommissionOrderStatus.UN_PAY.getCode());
        orderCommission.setOrderPrice(orderPrice);
        orderCommission.setTgRate(shippingQueryResult.getTgRate());
        orderCommission.setFxRate(shippingQueryResult.getFxRate());
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        orderCommission.setPayTime(dateFormat.format(now));
        double tg = Double.parseDouble(shippingQueryResult.getTgRate())/100;
        double fx = Double.parseDouble(shippingQueryResult.getFxRate())/100;
        orderCommission.setTgCommission(orderPrice.multiply(new BigDecimal(tg).setScale(2, BigDecimal.ROUND_HALF_UP)));
        orderCommission.setFxCommission(orderPrice.multiply(new BigDecimal(fx).setScale(2,BigDecimal.ROUND_HALF_UP)));
        orderCommission.setCommissionType(shareUserInfo.getVkState());
        if(shareUserInfo.getUserId().equals(userInfo.getUserParentId())){
            orderCommission.setBindType(1);
        }else{
            orderCommission.setBindType(2);
        }
        orderCommission.setCreateTime(DateUtils.getNowDateToString());
        orderCommission.setBindUserId(userInfo.getUserParentId());
        return orderCommission;
    }


    @Override
    public void confirmOrderPay(List<String> orderIdList){
        // 1.更新佣金订单状态为未入账
       int result = orderCommissionMapper.updateOrderStatusBatch(CommonType.CommissionOrderStatus.UN_SETTLE.getCode(),orderIdList);
       if(result>0){
           // 2.更新用户分享人数 增加首次邀请购买记录
          List<ShareGoodsVO> shareUserList = orderCommissionMapper.queryUserShareFirst(orderIdList);
          if(!CollectionUtils.isEmpty(shareUserList)) {
              userServiceClient.shareGoodsRecord(JSON.toJSONString(shareUserList));
          }
       }else{
           // 3.用户如果是第一次购买店铺商品 则成为店铺会员
           List<ShareGoodsVO> shareUserList = orderBaseMapper.queryFxOrderList(orderIdList);
           if(!CollectionUtils.isEmpty(shareUserList)) {
               userServiceClient.addShopVipUser(JSON.toJSONString(shareUserList));
           }

       }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateOrderAfterSale(String orderId){
        try {
            OrderCommissionVO orderCommission = orderCommissionMapper.selectByPrimaryKey(orderId);
            if (null != orderCommission) {
                ResponseResult resultResp = baseServiceClient.queryGoodsVkSet();
                GoodsVkSetVO goodsVkSet = JSON.parseObject(JSON.toJSONString(resultResp.getData()), GoodsVkSetVO.class);
                orderBaseMapper.updateOrderAfterSaleTime(orderId, DateUtils.getAfterDate(goodsVkSet.getAfterSalesDays()));
            }
            return ResponseResult.success();
        }catch (Exception e){
            logger.error(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.fail(0, "操作失败");
        }
    }

    @Override
    public void confirmVkApply(List<String> orderIdList){
        // 查询微客申请购买订单
        List<VkApplyOrderVO> vkApplyOrderList = orderCommissionMapper.queryVkApplyOrder(orderIdList);
        logger.info("vkApplyOrderList{}",JSON.toJSONString(vkApplyOrderList));
        if(!CollectionUtils.isEmpty(vkApplyOrderList)){
            Map<String,List<VkApplyOrderVO>> map = new HashMap<>();
            map.put("vkApplyOrderList",vkApplyOrderList);
            userServiceClient.vkApply(map);
        }
    }
}
